﻿using Helper;
using IoTClient;
using IoTClient.Clients.PLC;
using IoTClient.Common.Enums;
using IoTClient.Enums;
using Microsoft.Extensions.DependencyInjection;
using Model.EntityInfo;
using NLog;
using Sunny.UI;

namespace WinFormsSprayProcessSCADASystem
{
    public static class Globals
    {

        // 获取nlog实例
        public static readonly Logger NLogger = NLog.LogManager.GetCurrentClassLogger();
        // 获取logControler
        public static BLL.Manager.LogManager Logger { get; set; }


        // 公共属性，用于获取和设置 ServiceProvider 实例
        public static ServiceProvider CurrentServiceProvider { get; set; }
        public static IServiceProvider ServiceProvider { get; set; }
        public static IServiceScope ServiceScope { get; set; }

        // 静态字段，用于存储 IniFile 实例，使用延迟初始化
        private static IniFile iniFile;

        // 公共属性，用于获取和设置 IniFile 实例
        public static IniFile IniFile
        {
            get
            {
                // 延迟初始化 IniFile 实例
                if (iniFile == null)
                {
                    try
                    {
                        // 尝试创建 IniFile 实例，使用应用程序启动路径下的 Config.ini 文件
                        iniFile = new IniFile($"{Application.StartupPath}\\..\\config\\Config.ini");
                    }
                    catch (Exception ex)
                    {
                        // 处理初始化 IniFile 时可能出现的异常
                        Console.WriteLine($"初始化 IniFile 时出错: {ex.Message}");
                    }
                }
                return iniFile;
            }
            set => iniFile = value;
        }


        //PLC 变量配置文件的路径
        public static string PlcVarConfigPath { get; set; }


        //当前登录用户
        public static UserInfoModel CurrentUser { get; set; }


        //当前的有权限的路由列表
        public static List<RouteInfoModel> RouteList { get; set; }


        #region 西门子客户端相关配置文件
        //西门子客户端实例
        public static SiemensClient SiemensClient { get; set; }

        //CPU类型
        public static SiemensVersion CpuType { get; set; }

        //ip地址
        public static string IpAddress { get; set; }

        //端口号
        public static int Port { get; set; }

        //插槽
        public static byte Slot { get; set; }

        //机架号
        public static byte Rack { get; set; }

        //plc连接超时时间
        public static int ConnectTimeOut { get; set; }

        //plc读取间隔时间
        public static int ReadTimeInnterval { get; set; }

        //plc重连间隔时间
        public static int ReConnectTimeInnterval { get; set; }


        #endregion

        /// <summary>
        /// PLC变量字典 地址-类型
        /// </summary>
        public static Dictionary<string, DataTypeEnum> ReadDic = new Dictionary<string, DataTypeEnum>();

        /// <summary>
        /// PLC变量值 读取字典 名称-变量值
        /// </summary>
        public static Dictionary<string, object> DataDic = new Dictionary<string, object>();

        /// <summary>
        /// PLC变量值 写入字典 名称-地址
        /// </summary>
        public static Dictionary<string, string> WriteDic = new Dictionary<string, string>();

        /// <summary>
        ///  
        /// </summary>
        public static bool PlcWrite(string varName, dynamic value)
        {
            if (SiemensClient != null && SiemensClient.Connected)
            {
                string address = WriteDic[varName];
                Result res = SiemensClient.Write(address, value);
                if (res.IsSucceed)
                {
                    NLogger.Info($"{CurrentUser?.UserName}向PLC（{varName}）写入了（{value}）成功");
                    Logger?.CreateLogAsync(new BLL.DTO.LogDto.LogAddDto()
                    {
                        Content = $"{CurrentUser?.UserName}向PLC（{varName}）写入了（{value}）成功",
                        Level = (int)SystemEnums.Level.Log
                    });
                    return true;
                }

                NLogger.Error($"用户向PLC（{varName}）写入了（{value}）失败");
                Logger?.CreateLogAsync(new BLL.DTO.LogDto.LogAddDto()
                {
                    Content = $"{CurrentUser?.UserName}向PLC（{varName}）写入了（{value}）失败",
                    Level = (int)SystemEnums.Level.Error
                });
                return false;
            }
            else
            {
                UIMessageTip.ShowWarning("PLC连接异常");
                return false;
            }
        }

    }
}
